package com.ncloud.uniformInterface.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.aaaa.service.UserService;
import com.ncloud.chnl.service.CustAreaNodeService;
import com.ncloud.chnl.service.CustUserService;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.dubboservice.BsAttrInfoDubboService;
import com.ncloud.param.service.RequestCallServer;
import com.ncloud.uniformInterface.domain.RequestBodyView;
import com.ncloud.uniformInterface.domain.Result;
import com.ncloud.uniformInterface.utils.HttpClientUtils;
import com.ncloud.uniformInterface.utils.ResultUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * Created by shiqiang on 2017/6/22.
 */
@Api(value = "武汉可视化信息", description = "武汉可视化信息API", tags = "ncloud Api", basePath="/ncloud-api",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/api")
public class ApiController {
    private final static Logger logger = LoggerFactory.getLogger(ApiController.class);
    @Reference
    private RequestCallServer requestCallServer;
    @Reference
    private CustUserService custUserService;
    @Reference
    private BsAttrInfoDubboService bsAttrInfoDubboService;
    @Reference
    private CustAreaNodeService custAreaNodeService;
    @Reference
    private UserService userService;

  @ApiOperation(value="viewPlatform", notes="武汉可视化平台调用接口,systemCode平台系统编码，businessKey接口业务编码{gettenants\n" +
          "getapplianceinfo\n" +
          "gettenantlinkinfo\n" +
          "getAppinfo\n" +
          "getDeviceTrafficInfo\n" +
          "getlinkcmp\n" +
          "getdevlink\n" +
          "getweekappinfo\n" +
          "gethealthstatinfo\n" +
          "getDevBandwidth\n" +
          "getTenantLinkAllInfo}")
  @ApiImplicitParams({
          @ApiImplicitParam(name = "systemCode", value = "平台系统编码", required = true, dataType = "String"),
          @ApiImplicitParam(name = "businessKey", value = "接口业务编码", required = true, dataType = "String",allowableValues = "{a,b,c}"),
          @ApiImplicitParam(name = "json", value = "体内容信息，根据具体业务而定", required = false, dataType = "RequestBodyView" )
  })
    @SuppressWarnings(value="unchecked")
    @RequestMapping(value = "/wuhan/{systemCode}/{businessKey}", method = RequestMethod.POST)
    public Result<Object> viewPlatform(@PathVariable("systemCode") String systemCode, @PathVariable("businessKey") String businessKey ,
                                       HttpServletRequest request, @RequestBody RequestBodyView json) throws Exception{
      Long custId =null;
      Object userID = request.getAttribute("userID");
      //
      if (userID != null){
          logger.info("当前用户ID="+userID.toString());
          JSONObject param = new JSONObject();
          param.put("userId",Long.parseLong(userID.toString()));
          custId= custUserService.getCustByUserId(param);
          if(custId ==null){
              throw  new UserException("8888","当前操作人员不是客户，没有对应的信息用户客户关联信息！");
          }
      }else{
          throw  new UserException("8888","没有登录用户的userID！");
      }
      if(!"gettenants".equals(businessKey) && StringUtils.isEmpty(json.getTenantname())){
    	  JSONObject param = new JSONObject();
          param.put("id",custId);
          param.put("attrType","4");//客户类型
          param.put("attrCode","organizationName");
          JSONObject custAttr = bsAttrInfoDubboService.getBsAttr(param);
          if(custAttr!=null && custAttr.containsKey("attrValue")){
              json.setTenantname(custAttr.getString("attrValue"));
              logger.info("租户标识="+custAttr.getString("attrValue"));
          }else{
              throw  new UserException("8888","系统客户对应的租户信息不存在！");
          }
      }
      JSONObject param = new JSONObject();
      param.put("systemCode",systemCode);
      param.put("businessKey",businessKey);
      //设置客户信息
      param.put("custId",custId);
      param.putAll(JSON.parseObject(JSON.toJSONString(json)));
      //获取用户管理节点列表
      param.put("userID", userID);
      JSONArray nodeArray = getUserNodeList(param);
      String url = requestCallServer.getRequestUrl(param);
      HttpClientUtils clientUtils = new HttpClientUtils();
      String body = clientUtils.get(url);
      System.out.println("测试URL = " + url + "\t" + body);
      JSONObject bodyObj =null;
      if(!StringUtils.isEmpty(json.getConvertValue()) && "1".equals(json.getConvertValue())){
          bodyObj = requestCallServer.responseBodyDeal(body,param);
      }else{
          bodyObj = JSON.parseObject(body);
      }
      if(bodyObj.containsKey("code") && bodyObj.getIntValue("code") !=0){
          throw new UserException(bodyObj.getString("code")+"",bodyObj.getString("message"));
      }
      //过滤节点列表
      bodyObj = filterNodeList(bodyObj,nodeArray);
      logger.info("当前客户id="+custId);
      bodyObj.put("custId",String.valueOf(custId));
      return ResultUtil.success(bodyObj);
    }

	private JSONArray getUserNodeList(JSONObject json) {
		Long userId = Long.parseLong(json.getString("userID"));
		String businessKey = json.getString("businessKey");
		JSONArray nodeList = null;
		if("getDevBandwidth".equals(businessKey)){
			JSONObject user = userService.getUserById(userId);
			if("6".equals(user.getString("userType"))){
				nodeList = custAreaNodeService.getNodeListByUserId(userId);
			}else{
				return nodeList;
			}
		}
		return nodeList;
	}
	
	private JSONObject filterNodeList(JSONObject bodyObj, JSONArray nodeArray) {
		if(nodeArray==null) return bodyObj;
		if(!nodeArray.isEmpty()){
			JSONArray data = bodyObj.getJSONArray("data");
			JSONArray result = new JSONArray();
			for (Object object : data) {
				JSONObject dev = (JSONObject) object;
				String nodeId = dev.getString("nodeId");
				for (Object object2 : nodeArray) {
					JSONObject node = (JSONObject) object2;
					if(nodeId.equals(node.getString("nodeId"))){
						result.add(dev);
					}
				}
			}
			bodyObj.put("data", result);
		}else{
			bodyObj.put("data", null);
		}
		
		return bodyObj;
	}
}
